import Taro,{Component} from '@tarojs/taro'
import styles from './index.module.scss'
import { View } from '@tarojs/components'
import { getCitysByGeo } from '@/api/index'
import { connect } from '@tarojs/redux'
import { setCity } from '@/actions/home'

@connect(() => ({}),dispatch => ({
  setCity: (data) => dispatch(setCity(data))
}))
class Geo extends Component {

  config = {
    navigationBarTitleText: '地区'
  }

  state = {
    list: {}
  }

  componentWillMount() {
    this.getList()
  }

  getList = async () => {
    try {
      const {data} = await getCitysByGeo()
      this.setState({list: data})
    } catch(e) {
      Taro.showToast({icon: 'none', title: e.message })
    }
  }

  setCity = (city) => {
    this.props.setCity(city)
    Taro.navigateBack()
  }

  render() {
    const { list } = this.state
    return (
      <View className={styles.wrapper}>
        {
          Object.keys(list) && Object.keys(list).map(item => {
            return (
              <View key={item + ''} className={styles.item}>
                <View className={styles.title}>{item}</View>
                <View className={styles.ul}>
                  {
                    list[item].map(i => {
                      return (
                        <View key={i.id} className={styles.i} onClick={() => this.setCity(i.name)}>{i.name}</View>
                      )
                    })
                  }
                </View>
              </View>
            )
          })
        }
      </View>
    )
  }
}

export default Geo
